package com.example.demo.util;

import java.util.Calendar;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * json web token 工具类
 * 
 * @author zhou
 * @version 1.0.0
 */
public class JWTUtil {

  /** 盐 */
  public static String secret = "secret";
  /** ７天 */
  public static int expires = 7;

  /**
   * 获取token
   * 
   * @param name
   * @param password
   * @return
   */
  public static String getToken(String name, String password, int... arg) {

    Calendar instance = Calendar.getInstance();
    if (arg.length > 0) {
      instance.add(arg[0], arg[1]);
    } else {
      instance.add(Calendar.DATE, expires);
    }

    JWTCreator.Builder builder = JWT.create();

    builder.withClaim("name", name);
    builder.withClaim("password", password);
    builder.withExpiresAt(instance.getTime());

    return builder.sign(Algorithm.HMAC256(secret));
  }

  /**
   * 验证token
   * 
   * @param token
   * @return
   */
  public static boolean verify(String token) {
    if (token == null || token.isEmpty()) {
      return false;
    }

    try {

      JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
      verifier.verify(token);

      return true;
    } catch (Exception e) {
      // TODO
      return false;
    }
  }

  /**
   * 获取签发对象
   * 
   * @param token
   * @return
   */
  public static DecodedJWT getClaim(String token) {
    DecodedJWT jwt = JWT.decode(token);

    return jwt;
  }

}
